class TimeDomainAnalysis {
    constructor() {
        this.resultElement = document.getElementById('time-domain-result');
        this.loadingElement = document.getElementById('time-domain-loading');
        this.errorElement = document.getElementById('time-domain-error');
    }

    // 执行时域分析
    async performAnalysis(signal) {
        try {
            this.showLoading();
            
            // 发送请求到后端
            const response = await fetch('http://localhost:3300/analyze_time_series', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ signal: signal })
            });

            if (response.ok) {
                // 解析响应数据
                const result = await response.json();
                
                // 显示分析结果
                this.displayResults(result);
                
                // 隐藏加载状态
                this.hideLoading();
            } else {
                throw new Error('Failed to perform analysis');
            }
        } catch (error) {
            console.error('Error performing time domain analysis:', error);
            this.showError();
        }
    }

    // 显示分析结果
    displayResults(results) {
        // 清空现有内容
        this.resultElement.innerHTML = '';
        
        // 创建结果展示
        for (const [feature, value] of Object.entries(results)) {
            const featureElement = document.createElement('div');
            featureElement.textContent = `${feature}: ${value.toFixed(4)}`;
            this.resultElement.appendChild(featureElement);
        }
    }

    // 显示加载状态
    showLoading() {
        this.loadingElement.style.display = 'block';
        this.errorElement.style.display = 'none';
        this.resultElement.style.display = 'none';
    }

    // 隐藏加载状态
    hideLoading() {
        this.loadingElement.style.display = 'none';
        this.errorElement.style.display = 'none';
        this.resultElement.style.display = 'block';
    }

    // 显示错误状态
    showError() {
        this.loadingElement.style.display = 'none';
        this.errorElement.style.display = 'block';
        this.resultElement.style.display = 'none';
    }
}


class TimeDomainChart {
    constructor() {
        this.chartElement = document.getElementById('time-domain-chart');
        this.loadingElement = document.getElementById('time-domain-loading');
        this.errorElement = document.getElementById('time-domain-error');
        this.updateInterval = null;
        this.previousImageUrl = null;
    }

    // 开始自动更新
    startAutoUpdate() {
        console.log('TimeDomainChart: Starting auto update');
        // 确保元素存在再开始更新
        if (this.chartElement && this.loadingElement && this.errorElement) {
            console.log('TimeDomainChart: Elements found, starting update');
            this.updateChart();
            this.updateInterval = setInterval(() => {
                console.log('TimeDomainChart: Interval triggered');
                this.updateChart();
            }, 240000); // 每10秒更新一次
        } else {
            console.log('TimeDomainChart: Elements not found', {
                chart: this.chartElement,
                loading: this.loadingElement,
                error: this.errorElement
            });
        }
    }

    // 停止自动更新
    stopAutoUpdate() {
        console.log('TimeDomainChart: Stopping auto update');
        if (this.updateInterval) {
            clearInterval(this.updateInterval);
            this.updateInterval = null;
        }
        
        // 清理之前的图片URL
        if (this.previousImageUrl) {
            URL.revokeObjectURL(this.previousImageUrl);
            this.previousImageUrl = null;
        }
    }

    // 更新图表
    async updateChart() {
        try {
            console.log('TimeDomainChart: Updating chart');
            this.showLoading();
            
            // 生成测试信号数据
            const signal = this.generateTestSignal();
            console.log('TimeDomainChart: Signal generated, length:', signal.length);
            
            // 发送请求到后端
            console.log('TimeDomainChart: Sending request to /analyze_time_series_plot');
            const response = await fetch('http://localhost:3300/analyze_time_series_plot', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ signal: signal })
            });
            
            console.log('TimeDomainChart: Response received', response.status);

            if (response.ok) {
                // 清理之前的图片URL
                if (this.previousImageUrl) {
                    URL.revokeObjectURL(this.previousImageUrl);
                }
                
                // 将响应转换为图片URL
                const blob = await response.blob();
                this.previousImageUrl = URL.createObjectURL(blob);
                
                // 更新图片
                this.chartElement.src = this.previousImageUrl;
                this.chartElement.onload = () => {
                    // 图片加载完成后隐藏加载状态
                    console.log('TimeDomainChart: Image loaded');
                    this.hideLoading();
                };
            } else {
                console.error('TimeDomainChart: Failed to load chart, status:', response.status);
                throw new Error('Failed to load chart');
            }
        } catch (error) {
            console.error('TimeDomainChart: Error updating chart:', error);
            this.showError();
        }
    }

    // 生成测试信号
    generateTestSignal() {
        const length = 1000;
        const signal = [];
        for (let i = 0; i < length; i++) {
            // 生成包含正弦波和噪声的测试信号
            const sine = 0.8 * Math.sin(2 * Math.PI * 5 * i / 100) + 
                         0.2 * Math.sin(2 * Math.PI * 12 * i / 100);
            const noise = 0.1 * (Math.random() - 0.5);
            signal.push(sine + noise);
        }
        return signal;
    }

    // 显示加载状态
    showLoading() {
        console.log('TimeDomainChart: Showing loading');
        if (this.loadingElement && this.errorElement && this.chartElement) {
            this.loadingElement.style.display = 'block';
            this.errorElement.style.display = 'none';
            this.chartElement.style.display = 'none';
        }
    }

    // 隐藏加载状态
    hideLoading() {
        console.log('TimeDomainChart: Hiding loading');
        if (this.loadingElement && this.errorElement && this.chartElement) {
            this.loadingElement.style.display = 'none';
            this.errorElement.style.display = 'none';
            this.chartElement.style.display = 'block';
        }
    }

    // 显示错误状态
    showError() {
        console.log('TimeDomainChart: Showing error');
        if (this.loadingElement && this.errorElement && this.chartElement) {
            this.loadingElement.style.display = 'none';
            this.errorElement.style.display = 'block';
            this.chartElement.style.display = 'none';
        }
    }
}

document.addEventListener('DOMContentLoaded', () => {
new TimeDomainChart().startAutoUpdate();
new StftChart().startAutoUpdate();
});